package com.tran.app.repository

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import java.util.prefs.Preferences

class DataStoreManager(context: Context) {
    private val USER_PREFERENCES_NAME = "user_preferences"
    private val Context.dataStore by preferencesDataStore(
        name = USER_PREFERENCES_NAME
    )
    private val dataStore = context.dataStore
    /**
     * 写入数据
     * @param name String
     */
    suspend fun setTeachSp() {
        dataStore.edit { pref ->
            // pref[key] = name
            pref[pref_name] = true
        }
    }

    fun getTeachSp(): Flow<Boolean> {
        return dataStore.data.map { pref ->
            //根据 key 读取数据存入变量
          val  value = pref[pref_name] ?: false
            value
        }
    }


    companion object {
        //创建一个 key 变量，或者在外部传入 key 进来也行
        val pref_name = booleanPreferencesKey("isfirst")
    }

}